package com.sdx.console.transaction.web;

import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.console.order.service.FinOrderService;
import com.sdx.console.system.entity.ChannelSet;
import com.sdx.console.system.service.ChannelSetService;
import com.sdx.console.transaction.entity.FinTransaction;
import com.sdx.console.transaction.service.OrderListService;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * @ClassName OrderListController
 * @Description
 * @Author kangbin
 * @Date 2020/3/24 10:07
 */
@Controller
@RequestMapping("/trans/order")
public class OrderListController extends AuthorizedBaesController {

    private static final String MODEL = "/trans/order";

    @Resource
    private OrderListService orderListService;

    @Resource
    private CorePlatformService corePlatformService;

    @Resource
    private ChannelSetService channelSetService;

    @Resource
    private FinOrderService finOrderService;

    @Autowired
    FileService fileService;

    private void setPageParam(ModelAndView view, HttpServletRequest request) {

        view.addObject("orderTypes",finOrderService.selectOrderType(null));
        CoreUser user = getLoginUser(request);
        Integer accessType = corePlatformService.getAccessType(request);
        List<ChannelSet> channelList = channelSetService.selectAuthChannels(accessType, user.getOrgId(),user.getTenantId());
        view.addObject("channelList",channelList);

    }

    /* 页面 */
    @GetMapping("/index.do")
    @Function("trans.order.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
        setPageParam(view,request);
        return view;
    }


    @PostMapping("/list.json")
    @Function("trans.order.query")
    @ResponseBody
    public JsonResult<PageQuery> list(FinTransaction condtion, HttpServletRequest request)
    {
        PageQuery page = condtion.getPageQuery();
        orderListService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @PostMapping("/excel/export.json")
    @Function("trans.order.export")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response, FinTransaction condtion, HttpServletRequest request) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此finTransactionService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        CoreUser user = getLoginUser(request);
        condtion.setTenantId(user.getTenantId());
        String excelTemplate ="excelTemplates/trans/order.xls";
        PageQuery<FinTransaction> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        List<FinTransaction> list =orderListService.queryByCondition(page).getList();
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("交易记录_"+ DateUtil.now("yyyyMMddHHmmss")+".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }

    }



}
